package khiem.java.sample.genericgrapth;

import java.util.List;

import org.apache.commons.lang3.StringUtils;

public class Dependency {
  private String operator;
  private String targetNodeName;
  private String targetVersion;
  
  private String operator2;
  private String targetVersion2;
  
  public Dependency(String targetNodeName, String operator, String targetVersion) {
    this.operator = operator;
    this.targetNodeName = targetNodeName;
    this.targetVersion = targetVersion;
  }
  
  public Dependency(String targetNodeName, String operator, String targetVersion, String operator2, String targetVersion2) {
    this.operator = operator;
    this.targetNodeName = targetNodeName;
    this.targetVersion = targetVersion;
    this.operator2 = operator2;
    this.targetVersion2 = targetVersion2;
  }
  
  public String getOperator() {
    return operator;
  }
  public void setOperator(String operator) {
    this.operator = operator;
  }
  public String getTargetNodeName() {
    return targetNodeName;
  }
  public void setTargetNodeName(String targetNode) {
    this.targetNodeName = targetNode;
  }
  public String getTargetVersion() {
    return targetVersion;
  }
  public void setTargetVersion(String targetVersion) {
    this.targetVersion = targetVersion;
  }
  
  private boolean operate(String operator, String str1, String str2) {
    switch (operator) {
    case ">":
      return (str1.compareTo(str2) > 0);
    case ">=":
      return (str1.compareTo(str2) >= 0);
    case "<":
      return (str1.compareTo(str2) < 0);
    case "<=":
      return (str1.compareTo(str2) <= 0);
    case "=":
      return (str1.compareTo(str2) == 0);
    default:
      throw new IllegalArgumentException("Unknown operator \"" + operator + "\"");
    }
  }
  
  public boolean validateNode(GraphNode node) {
    if (!node.getName().equals(targetNodeName)) return false;
    boolean result1 = operate(operator, node.getVersion(), targetVersion);
    if (StringUtils.isNotEmpty(operator2)  && StringUtils.isNotEmpty(targetVersion2)) {
      return result1 && operate(operator2, node.getVersion(), targetVersion2);
    } else return result1;
  } 
  
  @Override
  public boolean equals(Object o) {
    Dependency dp = (Dependency) o;
    return (targetNodeName.equals(dp.getTargetNodeName()) && targetVersion.equals(dp.getTargetVersion())
        && operator.equals(dp.getOperator()));
  }
  
  @Override
  public String toString() {
    if (StringUtils.isNotEmpty(operator2)  && StringUtils.isNotEmpty(targetVersion2)) {
      return String.format("[%s %s %s, %s %s]", targetNodeName, operator, targetVersion, operator2, targetVersion2);
    } else return String.format("[%s %s %s]", targetNodeName, operator, targetVersion);
  }
  
}
